<template>
  <div>
    <Button
      variant="outline"
      size="sm"
      class="relative h-8 w-full justify-start rounded-[0.5rem] bg-white/10 text-sm text-white/80 hover:bg-white/20 sm:pr-12 md:w-40 lg:w-64"
      @click="open = true"
    >
      <Search class="mr-2 h-4 w-4" />
      <span class="hidden lg:inline-flex">搜索文章...</span>
      <span class="inline-flex lg:hidden">搜索...</span>
      <kbd
        class="pointer-events-none absolute right-1.5 top-1.5 hidden h-5 select-none items-center gap-1 rounded border border-white/20 bg-white/10 px-1.5 font-mono text-[10px] font-medium text-white/80 sm:flex"
      >
        <span class="text-xs">⌘</span>K
      </kbd>
    </Button>

    <CommandDialog v-model:open="open">
      <CommandInput placeholder="搜索文章..." />
      <CommandList>
        <CommandEmpty>未找到相关文章</CommandEmpty>
        <CommandGroup heading="搜索结果">
          <CommandItem
            v-for="article in searchResults"
            :key="article.id"
            @select="handleSelect(article)"
          >
            <div class="flex items-center gap-2">
              <LazyImage
                :src="article.thumbnail"
                :alt="article.title"
                wrapper-class="h-10 w-10 rounded"
                image-class="h-10 w-10 rounded object-cover"
                skeleton-class="h-10 w-10 rounded"
              />
              <div>
                <p class="text-sm font-medium">{{ article.title }}</p>
                <p class="text-xs text-gray-500">{{ article.categoryName }}</p>
              </div>
            </div>
          </CommandItem>
        </CommandGroup>
      </CommandList>
    </CommandDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useDebounce } from '@vueuse/core'
import { getArticleList } from '@/api/modules/content'
import type { Content } from '@/api/interface'
import { Search } from 'lucide-vue-next'
import {
  CommandDialog,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command'
import { Button } from '@/components/ui/button'
import LazyImage from '@/components/LazyImage/LazyImage.vue'

const router = useRouter()
const open = ref(false)
const searchResults = ref<Content.ResArticle[]>([])
const searchQuery = ref('')
const debouncedQuery = useDebounce(searchQuery, 300)

watch(debouncedQuery, async query => {
  if (!query) {
    searchResults.value = []
    return
  }
  const res = await getArticleList({
    title: query,
    pageNum: 1,
    pageSize: 5,
  })
  searchResults.value = res.data.list
})

const handleSelect = (article: Content.ResArticle) => {
  open.value = false
  router.push({
    name: 'detail',
    params: { id: article.id },
  })
}

const handleKeydown = (e: KeyboardEvent) => {
  if (e.key === 'k' && (e.metaKey || e.ctrlKey)) {
    e.preventDefault()
    open.value = true
  }
}

onMounted(() => {
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})
</script>
